<template>
  <div class="page">
    <div class="left-part" :class="{'actived':active}" id="canvasWrap">
      <div class="bg"></div>
      <img class="text" src="https://fdwebhost.oss-cn-huhehaote.aliyuncs.com/zhiyazhiyuan/images/login/text_02.png" alt="">
      <div class="progress" :class="{'ready':isReady}"></div>
    </div>
    <div class="right-part">
      <div class="title">知涯</div>
      <div class="steps" v-show="!showLogin">
        <div class="ceil" :class="{actived:step>=2,active:step==1}">
          <div class="text">手机注册</div>
          <div class="circle">1</div>
          <div class="line"></div>
        </div>
        <div class="ceil" :class="{actived:step>=3,active:step==2}">
          <div class="text">个人信息</div>
          <div class="circle">2</div>
          <div class="line"></div>
        </div>
        <div class="ceil" :class="{active:step==3}">
          <div class="text">绑定VIP</div>
          <div class="circle">3</div>
          <div class="line"></div>
        </div>
      </div>
      <!-- <template v-for="(item,index) in [2,3]">
        <div :key="index">{{item}}</div>
      </template> -->
      <form class="form-wrap" @submit.prevent="login('form1')" v-show="step==1" data-vv-scope="form1">
        <div class="item item-input item-stacked-label">
          <span class="label">手机号</span>
          <input type="text" placeholder="请输入手机号" name="phoneNum" data-vv-as="手机号码" v-model="loginParams.phoneNum" v-validate="'required|mobile'">
          <span v-show="errors.has('form1.phoneNum')" class="validate-help assertive">{{ errors.first('form1.phoneNum') }}</span>
        </div>
        <div class="item item-input item-stacked-label">
          <span class="label">验证码</span>
          <div class="input">
            <input type="text" placeholder="请输入验证码" name="verificationCode" data-vv-as="验证码" v-model="loginParams.verificationCode" v-validate="'required'">
            <button class="button button-dark" :disabled="errors.has('form1.phoneNum')||!loginParams.phoneNum||timer" type="button" @click="getCode">{{codeStr}}</button>
          </div>
          <span v-show="errors.has('form1.verificationCode')" class="validate-help assertive">{{ errors.first('form1.verificationCode') }}</span>
        </div>
        <div class="padding">
          <button class="button button-dark button-block" type="submit" :disabled="isLogin">{{showLogin?'登录':'下一步'}}</button>
          <nuxt-link class="text-right link" :to="linkString" tag="a">{{!showLogin?'已有账号，去登录? ':'没有账号，去注册? '}}</nuxt-link>
        </div>
      </form>
      <form class="form-wrap" v-show="step==2" @submit.prevent="competeInfo('form2')" data-vv-scope="form2">
        <div class="row">
          <div class="col-4">
            <div class="item item-input item-stacked-label">
              <span class="label">姓名</span>
              <input type="text" placeholder="请输入姓名" name="realname" data-vv-as="姓名" v-model="competeParams.name" v-validate="'required|chinese'">
              <span v-show="errors.has('form2.realname')" class="validate-help assertive">{{ errors.first('form2.realname') }}</span>
            </div>
          </div>
          <div class="col-3">
            <div class="item item-input item-stacked-label">
              <span class="label">性别</span>
              <div class="input">
                <label class="radio">
                  <input type="radio" v-model="competeParams.gender" :value="true">男
                </label>
                  <label class="radio">
                    <input type="radio" v-model="competeParams.gender" :value="false">女
                </label>
              </div>
            </div>
          </div>
          <div class="col-5">
            <div class="item item-input item-stacked-label">
              <span class="label">身份</span>
              <div class="input">
                <label class="radio">
                  <input type="radio" v-model="competeParams.userIdentity" :value="1">学生
                </label>
                <label class="radio">
                  <input type="radio" v-model="competeParams.userIdentity" :value="0">家长
                </label>
                <label class="radio">
                  <input type="radio" v-model="competeParams.userIdentity" :value="2">班主任
                </label>
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="row">
        </div> -->
        <div class="row">
          <div class="col-4">
            <div class="item item-input item-stacked-label">
              <span class="label">地点</span>
              <select name="province" data-vv-as="省份" v-model="competeParams.provinceId" v-validate="'required'" @change="selectChange('province')">
                <option value>请选择省份</option>
                <option v-for="(item,index) in provincesData" :key="index" :value="item.id">{{item.name}}</option>
              </select>
              <span v-show="errors.has('form2.province')" class="validate-help assertive">{{ errors.first('form2.province') }}</span>
            </div>
          </div>
          <div class="col-4">
            <div class="item item-input item-stacked-label">
              <span class="label">&nbsp;</span>
              <select name="city" data-vv-as="城市" v-model="competeParams.cityId" v-validate="'required'" @change="selectChange('city')">
                <option value>请选择城市</option>
                <option v-for="(item,index) in cityData" :key="index" :value="item.id">{{item.name}}</option>
              </select>
              <span v-show="errors.has('form2.city')" class="validate-help assertive">{{ errors.first('form2.city') }}</span>
            </div>
          </div>
          <div class="col-4">
            <div class="item item-input item-stacked-label">
              <span class="label">&nbsp;</span>
              <select name="area" data-vv-as="地区" v-model="competeParams.districtId" v-validate="'required'" @change="selectChange('district')">
                <option value>请选择地区</option>
                <option v-for="(item,index) in districtData" :key="index" :value="item.id">{{item.name}}</option>
              </select>
              <span v-show="errors.has('form2.area')" class="validate-help assertive">{{ errors.first('form2.area') }}</span>
            </div>
          </div>
        </div>
        <div class="item item-input item-stacked-label">
          <span class="label">学校</span>
          <select name="school" data-vv-as="学院" v-model="competeParams.school" v-validate="'required'">
            <option value>请选择学校</option>
            <option v-for="(item,index) in schoolData" :key="index" :value="item.id">{{item.name}}</option>
          </select>
          <span v-show="errors.has('form2.school')" class="validate-help assertive">{{ errors.first('form2.school') }}</span>
        </div>
        <div class="item item-input item-stacked-label">
          <span class="label">年级</span>
          <select name="entry" data-vv-as="年级" v-model="competeParams.startYear" v-validate="'required'">
            <option value>请选择年级</option>
            <option v-for="(item,index) in yearData" :key="index" :value="item">{{item}}</option>
          </select>
          <span v-show="errors.has('form2.entry')" class="validate-help assertive">{{ errors.first('form2.entry') }}</span>
        </div>
        <div class="padding">
          <button class="button button-dark button-block">下一步</button>
        </div>
      </form>
      <form class="form-wrap" v-show="step==3" @submit.prevent="bindCard('form3')" data-vv-scope="form3">
        <div class="item item-input item-stacked-label">
          <span class="label">VIP卡号</span>
          <input type="text" placeholder="请输入VIP卡号" name="card" data-vv-as="VIP卡号" v-model="bindParams.cardNumber" v-validate="'required'">
          <span v-show="errors.has('form3.card')" class="validate-help assertive">{{ errors.first('form3.card') }}</span>
        </div>
        <div class="item item-input item-stacked-label">
          <span class="label">VIP密码</span>
          <input type="password" placeholder="请输入VIP密码" name="cardpwd" data-vv-as="VIP密码" v-model="bindParams.password" v-validate="'required'">
          <span v-show="errors.has('form3.cardpwd')" class="validate-help assertive">{{ errors.first('form3.cardpwd') }}</span>
        </div>
        <div class="padding">
          <button class="button button-dark button-block">完成</button>
        </div>
        <div @click="toHome" class="to-home">
          跳过 >
        </div>
      </form>

    </div>
  </div>
</template>

<script>
import { api } from '@/utils'
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
  layout: 'default',
  data () {
    return {
      isLogin: false,
      isReady: false,
      active: false,
      loginParams: {

      },
      competeParams: {
        gender: true,
        provinceId: '',
        cityId: '',
        districtId: '',
        school: '',
        startYear: '',
        userIdentity: 1
      },
      bindParams: {

      },
      timer: null,
      codeStr: '获取验证码',
      show: false,
      provincesData: [],
      cityData: [],
      districtData: [],
      schoolData: [],
      yearData: ['高一', '高二', '高三']
    }
  },
  computed: {
    step () {
      return this.$route.query.step ? this.$route.query.step : 1
    },
    linkString () {
      return this.$route.query.type === 'login' ? '/login?type=regist' : '/login?type=login'
    },
    showLogin () {
      return this.$route.query.type === 'login' ? true : false
    },
    ...mapState({
      authInfo: 'authInfo'
    })
  },
  methods: {
    ...mapMutations(['SET_AUTH_INFO']),
    ...mapActions(['getUserInfo']),
    filterCityDistrict (arr, id) {
      for (let key in arr) {
        let item = arr[key]
        if (item.id === id) return item
      }
    },
    selectChange (type) {
      if (type === 'province') {
        this.cityData = []
        this.districtData = []
        this.schoolData = []
        this.competeParams.cityId = ''
        this.competeParams.districtId = ''
        this.competeParams.school = ''
        // this.competeParams.provinceId && this.$axios.get(`${api.cities}/${this.competeParams.provinceId}/cities`).then(data => {
        //   this.cityData = data._embedded.cities
        // })
        this.competeParams.provinceId && (this.cityData = this.filterCityDistrict(this.provincesData, this.competeParams.provinceId).cities)
      } else if (type === 'city') {
        this.districtData = []
        this.schoolData = []
        this.competeParams.districtId = ''
        this.competeParams.school = ''
        // this.competeParams.cityId && this.$axios.get(`${api.districts}/${this.competeParams.cityId}/districts`).then(data => {
        //   this.districtData = data._embedded.districts
        // })
        this.competeParams.cityId && (this.districtData = this.filterCityDistrict(this.cityData, this.competeParams.cityId).districts)
      } else if (type === 'district') {
        this.schoolData = []
        this.competeParams.school = ''
        this.competeParams.districtId && this.$axios.get(api.findScholl, {
          params: {
            districtId: this.competeParams.districtId
          }
        }).then(data => {
          this.schoolData = data._embedded.schools
        })
      }
    },
    getCode () {
      let seconds = 150
      this.timer = true
      this.$axios.get(`${api.sendSms}/${this.loginParams.phoneNum}`).then(data => {
        if (data.code === 'ok') {
          this.timer = setInterval(() => {
            if (seconds > 0) {
              seconds--
              this.codeStr = `${seconds}s后失效`
            } else {
              this.codeStr = '重新发送'
              clearInterval(this.timer)
              this.timer = null
            }
          }, 1000)
        } else {
          this.$toasted.error(data.message)
          this.timer = null
        }
      }).catch(() => {
        this.timer = null
        this.$toasted.error('接口调用失败')
      })
    },
    login (scope) {
      this.$validator.validateAll(scope).then((result) => {
        if (result) {
          this.isLogin = true
          this.$axios.post(api.webLogin, this.loginParams).then(data => {
            if (data.token) {
              //  this.$toasted.success('验证手机号码成功')
              this.SET_AUTH_INFO({
                token: data.token,
                level: data.level, // 会员等级
                isValid: data.isValid, // 会员是否可用
                dataFlag: data.dataFlag, // 是否完善信息
                userCenterId: data.userCenterId,
                phoneNum: data.phoneNum
              })
              if (!data.dataFlag) {
                this.$router.replace({
                  name: 'login',
                  query: {
                    step: 2
                  }
                })
                this.isLogin = false
              } else if (data.dataFlag && !data.level) {
                this.$router.replace({
                  name: 'login',
                  query: {
                    step: 3
                  }
                })
                this.isLogin = false
              } else if (data.dataFlag && data.level) {
                this.getUserInfo(this)
                location.replace('/')
              }
            } else {
              this.$toasted.error(data.msg)
              this.isLogin = false
            }
          })
        }
      }).catch(() => {
        this.$toasted.error('网络出现故障')
        this.isLogin = false
      })
    },
    competeInfo (scope) {
      this.$validator.validateAll(scope).then((result) => {
        if (result) {
          let { school, gender, provinceId, cityId, districtId, startYear, name, userIdentity } = this.competeParams
          this.$axios.post(api.personData, {
            gender: gender,
            name,
            startYear,
            //  id: this.$store.state.userCenterId,
            school: {
              id: school
            },
            // address: {
            province: {
              id: provinceId
            },
            city: {
              id: cityId
            },
            district: {
              id: districtId
            },
            userIdentity: userIdentity
            // }
          }).then(data => {
            console.log(data)
            this.$toasted.success('完善信息成功')
            let authInfo = this.lodash.cloneDeep(this.authInfo)
            authInfo.dataFlag = true
            this.SET_AUTH_INFO(authInfo)
            this.getUserInfo(this)
            this.$router.replace({
              name: 'login',
              query: {
                step: 3
              }
            })
          }).catch(() => {
            this.$toasted.error('接口调用失败')
          })
        }
      })
    },
    toHome () {
      this.getUserInfo(this)
      location.replace('/')
    },
    bindCard (scope) {
      this.$validator.validateAll(scope).then((result) => {
        if (result) {
          let authInfo = this.authInfo
          this.$axios.post(api.bindingCard, {
            ...this.bindParams,
            phoneNumber: authInfo.phoneNum
          }).then(data => {
            let authInfo = this.lodash.cloneDeep(this.authInfo)
            authInfo.isValid = true
            authInfo.level = data.level
            this.SET_AUTH_INFO(authInfo)
            this.getUserInfo(this)
            location.replace('/')
          }).catch(err => {
            this.$toasted.error(err.data.message)
          })
        }
      })
    }
  },
  mounted () {
    this.isReady = true
    setInterval(() => {
      this.active = !this.active
    }, 3000)
    /* for (let i = 0; i < 4; i++) {
      this.yearData[i] = formatDate(new Date(), 'yyyy') - i
    } */
    // this.$axios.get(api.provinces).then(data => {
    //   this.provincesData = data._embedded.provinces
    // })
    this.$axios.get(api.area).then(data => {
      this.provincesData = data
    })
    window.requestAnimFrame = (function () {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function (callback) {
          window.setTimeout(callback, 1000)
        }
    })()
    const canvasWrap = document.getElementById('canvasWrap')
    let canvas = document.createElement('canvas')
    let w = canvasWrap.offsetWidth
    let h = canvasWrap.offsetHeight
    canvas.width = w
    canvas.height = h
    canvasWrap.appendChild(canvas)
    let ctx = canvas.getContext('2d')
    let mols = []

    function init () {
      const logoImg = 'https://fdwebhost.oss-cn-huhehaote.aliyuncs.com/zhiyazhiyuan/images/login/fill07.png'
      let image = new Image()
      image.src = logoImg
      image.onload = function () {
        let mol
        mol = new DrawImg('logo', image)
        mol && mols.push(mol)
      }
    }
    function draw () {
      canvas.width = canvas.width
      for (let i = 0; i < mols.length; i++) {
        let m = mols[i]
        m.x += m.vx
        if (m.x > m.orgx || m.x < -m.orgx) {
          m.vx = -m.vx
        }
        m.y += m.vy
        if (m.y > m.orgy || m.y < -m.orgy) {
          m.vy = -m.vy
        }
        m.r += 0.005
        m.draw()
      }
    }
    function DrawImg (type, img) {
      let width = img.width / 2.5
      let height = img.height / 2.5
      let orgx, orgy
      orgx = 100
      orgy = 60
      this.x = Math.random() * orgx
      this.y = Math.random() * orgy
      this.orgx = orgx
      this.orgy = orgy
      this.vx = Math.random() * -0.8
      this.vy = Math.random() * 0.8
      this.r = Math.random() * Math.PI
      this.w = width
      this.h = height
      this.type = type
      this.draw = function () {
        ctx.save()
        ctx.translate(-this.x, -this.y)
        /* ctx.rotate(this.r) */
        ctx.drawImage(img, (w - this.w) / 2, 0, this.w, this.h)
        ctx.restore()
      }
    }

    init()

    function animate () {
      window.requestAnimFrame(animate)
      draw()
    }
    animate()
    /* this.$axios.get(api.area).then(data => {
      alert(data)
    }) */
  }
}
</script>

<style scoped lang="scss">
@keyframes progress {
  from {
    transform: scale3d(0, 1, 1);
    transform-origin: 0 0;
  }
  to {
    transform: scale3d(1, 1, 1);
    transform-origin: 0 0;
  }
}
.page {
  display: flex;
  height: 100vh;
  .to-home {
    text-align:center;
    margin-top:30px;
    color: #666;
    cursor:pointer;
  }
  .left-part {
    width: 40%;
    height: 100%;
    max-width: 563px;
    min-width: 400px;
    overflow: hidden;
    position: relative;
    img.text {
      position: absolute;
      left: 25px;
      width: 60%;
      top: 45%;
      transition: opacity ease 0.5s;
      opacity: 0;
    }
    > div {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
    }
    .progress {
      width: 132px;
      height: 8px;
      border-radius: 12.5px;
      overflow: hidden;
      background: $light;
      position: absolute;
      top: 72px;
      left: 50%;
      margin-left: -66px;
      z-index: 4;
      padding: 2px;
      display: none;
      &:before {
        content: "";
        display: block;
        background: $positive;
        width: 100%;
        height: 4px;
        transition: transform ease 0.5ss;
      }
      &.ready {
        &:before {
          animation: progress 10s linear infinite;
        }
      }
    }
    /deep/ canvas {
      position: relative;
      z-index: 3;
      display: block;
    }
    .bg {
      background: url("https://fdwebhost.oss-cn-huhehaote.aliyuncs.com/zhiyazhiyuan/images/login/login_bg_02.jpg")
        repeat;
      &:before {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: url("https://fdwebhost.oss-cn-huhehaote.aliyuncs.com/zhiyazhiyuan/images/login/login_bg_01.jpg")
          left bottom no-repeat;
        background-size: 100% auto;
      }
    }

    &.actived {
      img.text {
        opacity: 1;
      }
      .bg {
        background: url("https://fdwebhost.oss-cn-huhehaote.aliyuncs.com/zhiyazhiyuan/images/login/login_bg_03.jpg")
          #3cd2d3 left bottom no-repeat;
        background-size: 100% auto;
        &:before {
          display: none;
        }
      }
      .progress {
        &:before {
          background: #3cd2d3;
        }
      }
    }
  }
  .right-part {
    flex: 1;
    overflow: auto;
    padding: 120px 64px;
    .steps {
      display: flex;
      width: 450px;
      margin: 66px auto 100px;
      .ceil {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        position: relative;
        flex: 1;
        &.actived {
          .circle {
            background: $positive;
          }
        }
        &.active {
          .circle {
            background: $dark;
          }
        }
        &:first-child {
          .line {
            left: 50%;
          }
        }

        &:last-child {
          .line {
            right: 50%;
          }
        }
      }
      .circle {
        width: 32px;
        height: 32px;
        background: $stable;
        border-radius: 50%;
        border: 3px solid $light;
        position: relative;
        box-sizing: content-box;
        color: $light;
        text-align: center;
        line-height: 32px;
        z-index: 1;
      }
      .line {
        height: 2px;
        background: $dark;
        position: absolute;
        right: 0;
        left: 0;
        bottom: 15px;
      }
      .text {
        font-size: 20px;
        padding: 0 0 10px 0;
      }
    }
    .title {
      font-size: 36px;
      text-align: center;
    }
  }
  .form-wrap {
    width: 500px;
    margin: 0 auto;
    font-weight: bold;
    .item {
      padding-top: 8px;
      padding-bottom: 8px;
      .label {
        font-weight: bold;
      }
    }
  }
  .padding {
    padding-top: 30px;
    .link {
      padding: 10px 0;
      display: inline-block;
      float: right;
    }
  }
  .row .col-4 {
    &:not(:last-child) {
      padding-right: 10px;
    }
  }
  .row .col-6 {
    &:not(:last-child) {
      padding-right: 10px;
    }
  }
}
</style>
